package gamecomponents.sound;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

/**
 * Plays sounds.
 * @author Team Deer
 * 
 */
public class SoundManager {

	private static SoundManager singletonInstance;

	private final Map<String, SoundClip> database = new HashMap<String, SoundClip>();

	// Constructor and singleton getter
	
	private SoundManager() {
		// w/e
	}

	/**
	 * 
	 * @return - The one and only instance of a view
	 */
	public static SoundManager getInstance() {
		if (singletonInstance == null) {
			singletonInstance = new SoundManager();
		}
		return singletonInstance;
	}

	// Methods
	
	/**
	 * 
	 * @param name
	 * @param filename
	 * @return returns true if the file was added with success.
	 */
	public boolean addSound(final String name, final String filename) {
		try {
			this.database.put(name, new SoundClip(filename));
		} catch (final UnsupportedAudioFileException e) {
			return false;
		} catch (final IOException e) {
			return false;
		} catch (final LineUnavailableException e) {
			return false;
		}
		return true;
	}

	/**
	 * Play the sound with the given name
	 * 
	 * @param name
	 *            - name of the sound to play
	 */
	public void playSound(final String name) {
		final SoundClip soundClip = this.database.get(name);
		if (!soundClip.isRunning()) {
			new Thread(soundClip).start();
		}
	}

}